<template>
  <el-badge :value="badgeValue" class="bounceIn" :offset="[-16, 0]">
    <div
      v-if="runwayStatus && showContent"
      :class="[
        'card-wrapper',
        'runway-card',
        opMode == 'NSWJ' ? 'runway-card-danger' : '',
        opMode == 'NSWJ' ? 'shake-fast-slightly' : '',
      ]"
      @click="cardClick"
      @contextmenu.prevent="cardRightClick"
      @mousemove="isHovering = true"
      @mouseout="isHovering = false"
    >
      <el-scrollbar height="160px">
        <div class="runway-card-content">
          <rowContent
            v-for="icao in airportCodes"
            :icao="icao"
            :runwayStatus="runwayStatus"
          />
        </div>
      </el-scrollbar>
    </div>
  </el-badge>
</template>

<script setup>
import { ref, computed, h, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import dayjs from "dayjs";
import useAcrtivityStore from "@/store/activity.js";
import rowContent from "./rowContent.vue";

const activityStore = useAcrtivityStore();

const showContent = ref(true);
const isHovering = ref(false);
const badgeValue = ref("");
const isExpired = ref(false);
const badgeType = ref("info");

const runwayStatus = ref(null);

const opMode = computed(() => activityStore.opMode);

const lastCodes = ref({
  ZUUU: "",
  ZUTF: "",
  ZUMY: "",
});

const lastChangeTime = ref(-1);

const lastLoadingMinutes = ref(-1);

const isNew = ref(false);

const airportRunwayInfo = {
  ZUUU: {
    N: ["02L", "02R"],
    S: ["20R", "20L"],
  },
  ZUTF: {
    N: ["01", "02", "11"],
    S: ["19", "20", "11"],
  },
  ZUMY: {
    N: ["32"],
    S: ["14"],
  },
};

const airportCodes = computed(() => Object.keys(airportRunwayInfo));

const checkUpdate = () => {
  if (!activityStore.runwayLoaded) {
    console.log("[runwayStatus]", "Not loaded yet!");
    return null;
  }
  runwayStatus.value = computeRunwayStatus();
  // console.log("[runwayStatus]", "checkUpdate...", runwayStatus.value);

  lastLoadingMinutes.value = Math.round(
    (new Date().getTime() - activityStore.runwayVersion) / 60000
  );

  let changed = false;
  isExpired.value = false;

  let msg = new Array();
  Object.keys(airportRunwayInfo).forEach((icao) => {
    if (lastCodes.value[icao] != activityStore["runwayCode" + icao]) {
      if (lastCodes.value[icao] != "") {
        changed = true;
        msg.push(
          h("div", { style: { marginBottom: "4px" } }, [
            h(
              "div",
              { style: { fontWeight: "bolder" } },
              icao + "跑道模式已更新"
            ),
            h(
              "div",
              null,
              `起飞跑道：${runwayStatus.value.usages[icao].dep.join(" ")}`
            ),
            h(
              "div",
              null,
              `落地跑道：${runwayStatus.value.usages[icao].arr.join(" ")}`
            ),
          ])
        );
      }
      lastCodes.value[icao] = activityStore["runwayCode" + icao];
    }
  });

  if (changed) {
    isNew.value = true;
    lastChangeTime.value = new Date().getTime();
    badgeType.value = "warning";
    badgeValue.value = "更新";
    refreshView();
    msg.push(
      h(
        "div",
        {
          style: {
            paddingTop: "4px",
            fontSize: "12px",
            opacity: "0.5",
          },
        },
        "@" + dayjs().format("HH:mm:ss")
      )
    );
    ElNotification({
      type: "warning",
      message: h("div", null, msg),
      duration: 60 * 1000,
      position: "bottom-right",
    });
    console.log("[runwayStatus]", "Runway changed!", runwayStatus.value);
  }

  let timestamp = new Date().getTime();
  if (timestamp - lastChangeTime.value > 90 * 1000) {
    badgeValue.value = "";
    badgeType.value = "info";
    isNew.value = false;
  }

  if (timestamp - activityStore.runwayVersion > 180 * 1000) {
    isExpired.value = true;
    badgeValue.value = "过期";
    badgeType.value = "danger";
  }
};

const refreshView = async () => {
  showContent.value = false;
  await nextTick();
  showContent.value = true;
};

const computeRunwayStatus = () => {
  // Get the runway codes and modes from the store

  let codes = {};
  let direction = {};
  let usageCodes = {};
  let usages = {};

  Object.keys(airportRunwayInfo).forEach((icao) => {
    let targetCode = activityStore["runwayCode" + icao];
    codes[icao] = targetCode;
    direction[icao] = targetCode.substring(0, 1);
    usageCodes[icao] = Array.from(targetCode.substring(1, targetCode.length));
    usages[icao] = {
      dep: airportRunwayInfo[icao][direction[icao]]
        .map((cell, idx, arr) => {
          if (usageCodes[icao][idx] == 1 || usageCodes[icao][idx] == 3) {
            return cell;
          } else {
            return null;
          }
        })
        .filter((cell) => cell != null),
      arr: airportRunwayInfo[icao][direction[icao]]
        .map((cell, idx, arr) => {
          if (usageCodes[icao][idx] == 2 || usageCodes[icao][idx] == 3) {
            return cell;
          } else {
            return null;
          }
        })
        .filter((cell) => cell != null),
    };
  });

  return { codes, direction, usageCodes, usages };
};

const cardClick = () => {};
const cardRightClick = () => {
  ElMessage({
    type: "info",
    message: `跑道信息更新于${lastLoadingMinutes.value}分钟前`,
  });
};

const timer = ref(null);

onMounted(() => {
  checkUpdate;
  timer.value = setInterval(() => checkUpdate(), 1000);
});

onUnmounted(() => {
  clearInterval(timer.value);
});
</script>

<style scoped>
@import "@/styles/card.css";
@import "@/styles/shake.css";

.runway-card {
  background: linear-gradient(135deg, #3282b8, #425066);
  height: 160px;
  font-size: 12px;
  text-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
}

.runway-card-danger {
  background: linear-gradient(135deg, #f67280, #6a465e);
}

.runway-card-content {
  width: 160px;
  padding: 8px 0 4px 0;
  margin: 0;
  /* text-align: center; */
}
</style>

<style>
@import "@/styles/colors.css";
</style>
